import axios from 'axios'
import router from '../router/index'
import { Message } from 'element-ui'
import {
  Notification
} from 'element-ui'
import store from '../store/index'
// import {
//     getToken
// } from '@/utils/auth'

// 创建axios实例
const service = axios.create({
  baseURL: '', // api 的 base_url
  timeout: 10 * 60 * 1000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    config.headers['token'] = sessionStorage.getItem("token");
    // if (sessionStorage.getItem("token") && !config.hasAuth) {
    //     config.headers['authorization'] =  sessionStorage.getItem("token"); // 让每个请求携带自定义token 请根据实际情况自行修改
    // }
    // let userInfo = '';
    // if(sessionStorage.userInfo){
    //   userInfo = JSON.parse(sessionStorage.userInfo);
    // }
    // if(userInfo && !config.userInfo){
    //   config.headers['UserUuid'] = userInfo.uuid;
    // }
    return config
  },
  error => {
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    /**
     * code为非20000是抛错 可结合自己业务进行修改
     */
    const res = response.data
    if (res.errcode == 201) {
      Message({
        message: res.errmsg,
        type: 'error',
        duration: 5 * 1000
      });
      router.push({ path: '/login', replace: true })
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    if (String(error).indexOf('timeout') != -1) {
      Notification({
        message: '查询超时，请重试',
        type: 'error',
        duration: 1 * 1000
      });
      return Promise.reject(error)
    } else {
      Notification({
        message: '系统繁忙',
        type: 'error',
        duration: 1 * 1000
      });
      return Promise.reject(error)
    }
  }
)

export default service
